package com.alogic.loki.handler;

import com.alogic.loki.LokiStream;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.stream.Handler;
import com.anysoft.stream.ScriptHandler;
import com.anysoft.util.*;
import org.w3c.dom.Element;

import java.util.HashMap;
import java.util.Map;

/**
 * 脚本处理
 *
 * @since 1.6.13.14 [20200907 duanyy] <br>
 */
public class Script extends ScriptHandler<LokiStream> {
    @Override
    protected void onConfigure(Element e, Properties p) {
        super.onConfigure(e, p);
    }

    @Override
    protected void onHandle(LokiStream data, long timestamp) {
        if (stmt == null){
            LOG.error("The script is null");
            return ;
        }
        LogicletContext ctx = new LogicletContext(Settings.get());
        try {
            Map<String, Object> root = new HashMap<String, Object>();
            XsObject doc = new JsonObject("root",root);
            ctx.setObject("$loki-stream",data);
            stmt.execute(doc, doc, ctx, null);
        } catch (Exception t) {
            LOG.error("Failed to execute script", t);
        }finally {
            ctx.removeObject("$loki-stream");
        }
    }
}

